package com.nowcoder.community.a_aop;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;


@Component
@Aspect
public class MingHanAspect {
    private static final Logger logger = LoggerFactory.getLogger(MingHanAspect.class);
    private static int i = 1;
    //在哪个方法前捕获
    @Pointcut("execution(* com.nowcoder.community.d_controller.*.*(..))")
    public void pointcut(){
    }

    //在捕获方法之前输出
    @Before("pointcut()")
    public void before(JoinPoint joinPoint){
        //生背
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(attributes==null) return;//空指针异常，直接改return暴力

        HttpServletRequest request = attributes.getRequest();

        String ip = request.getRemoteHost();
        String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        String target = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        // 用户[1.2.3.4],在[xxx],访问了[com.nowcoder.community..d_controllerxxx.xxx()].
        logger.info(String.format("\n\n"+"第[%d]步————访问了[%s]."+"\n",i,target));
        i++;
    }
}
